<?php
// *** Tangra (Application Framework and Tools for PHP)
// $Id$
//

require_once(TANGRA_MAIN_DIR.'web_site/tple_exports.class.php');
require_once(TANGRA_MAIN_DIR.'web_site/web_page/web_page_view.class.php');

class Vanilla_Web_Page_View extends Web_Page_View {
	private $view;
	private $pages_tpl_path;
	private $subdir;
	protected $exports;

	function __construct(Web_Page $page, $name = 'default', $pages_tpl_path = NULL, $subdir = NULL) {
		parent::__construct($page, $name);

		if ($pages_tpl_path) {
			$this->set_pages_tpl_path($pages_tpl_path);
		} else {
			$this->set_pages_tpl_path('pages/');
		}

		$this->set_subdir($subdir);
	}


	public function get_page_name() {
		return $this->get_page()->get_page_name();
	}


	public function get_view() {
		return $this->view;
	}


	public function set_pages_tpl_path($pages_tpl_path) {
		$this->pages_tpl_path = $pages_tpl_path;
	}


	public function get_pages_tpl_path() {
		return $this->pages_tpl_path;
	}


	public function set_subdir($subdir) {
		$this->subdir = tangra_normalize_path($subdir);
	}


	public function get_subdir() {
		return $this->subdir;
	}


	public function &fetch_content() {
		global $WSC;

		$tple = New Tple();

		$page = $this->get_page();
		$this->add_exports($page->get__exports());

		$this->process_exports($tple);

		$tpl_resource = $this->compose_tpl_resource_path($tple->get_tpl_dir());

		$ret['html'] = $tple->fetch($tpl_resource);
		$ret['exports'] = $this->get__exports();

		return $ret;
	}


	public function show() {

		foreach($this->get_http_headers() as $h) {
			header($h);
		}

		$this->export('_additional_csses', $this->get_additional_csses());
		$this->export('_additional_jses', $this->get_additional_jses());

		$rez = $this->fetch_content();
		print($rez['html']);
	}


	protected function compose_tpl_resource_path($tpl_path) {
		$tpl_file = $this->get_pages_tpl_path().$this->get_subdir().$this->get_page_name().'.tpl';

		if (file_exists(tangra_normalize_path($tpl_path).$tpl_file)) {
			$tpl_file = $this->get_pages_tpl_path().$this->get_subdir().$this->get_page_name().'.tpl';
		} else {
			$tpl_file = $this->get_pages_tpl_path().'_switch.tpl';
		}

		return $tpl_file;
	}


	protected function process_exports(Tple &$tple) {
		$config = $this->get_page()->get__config();

		$arr = $this->get__exports()->get_pairs();

		foreach($arr as $key => $value) {
			$tple->assign($key, $value);
		}

		$tple->assign('_path', tangra_normalize_path($this->get_pages_tpl_path()));
		$tple->assign('_page', $this->get_page_name());
		$tple->assign('_view', $this->get_name());
		$tple->assign('_subdir', $this->get_subdir());
		$tple->assign('_language', $config->get_current_language());
		$tple->assign('_current_host', $config->get_current_host());
		$tple->assign('_current_port', $config->get_current_port());
		$tple->assign('_current_protocol', $config->get_current_protocol());
	}
}

